//渲染学生信息列表
getStudentList()

//初始化添加学员的省市县下拉框
initSelect('#addModal')

//初始化修改学员的省市县下拉框
initSelect('#updateModal')


function initSelect(domName) {
  //获取省，市，县对应的select下拉框的dom元素
  const provineSelectDom = document.querySelector(`${domName} select[name=province]`)
  const citySelectDom = document.querySelector(`${domName} select[name=city]`)
  const countySelectDom = document.querySelector(`${domName} select[name=county]`)

  //渲染省份下拉框
  renderSelect('/geo/province', provineSelectDom, '省')

  // 监听省份change事件渲染对应省份下的市级
  provineSelectDom.addEventListener("change", function () {
    renderSelect('/geo/city', citySelectDom, '市', {
      pname: provineSelectDom.value
    })
  })

  // 监听市级change事件渲染对应省份和市级下的县
  citySelectDom.addEventListener("change", function () {
    renderSelect('/geo/county', countySelectDom, '县', {
      pname: provineSelectDom.value,
      cname: citySelectDom.value
    })
  })
}
/* 
renderSelect函数
*url: 接口地址，必填
*selectDom：下拉框的dom元素，必填
*keyWord："省"or"市"or"县"，必填
*params:接口对象参数 ,可填
*/
function renderSelect(url, selectDom, keyWord, params) {
  //判断存在接口参数
  if (params) {
    let arr = []
    for (let key in params) {
      arr.push(`${key}=${params[key]}`)
    }
    //拼接字符串成?a=1&b=2格式
    url += '?' + arr.join('&')
  }

  return axios.get(url)
    .then(res => {
      let { data: result } = res
      let html = result.reduce((sum, value) =>
        sum + `<option  value="${value}">${value}</option>`,
        `<option selected value="">--${keyWord}--</option>`)
      if (selectDom) {
        selectDom.innerHTML = html
      }
    })
    .catch(res => {

    })
}

//获取学生信息函数
function getStudentList() {
  axios.get('/student/list')
    .then(res => {
      let { data: result } = res
      // console.log(result);
      if (result.code === 0) {
        let StudentList = result.data
        // console.log(StudentList);
        let html = StudentList.reduce((sum, value) => sum + `
        <tr>
        <th scope="row">${value.id}</th>
        <td>${value.name}</td>
        <td>${value.age}</td>
        <td>${value.sex}</td>
        <td>${value.group}</td>
        <td>${value.phone}</td>
        <td>${value.salary}</td>
        <td>${value.truesalary}</td>
        <td>${value.province + value.city + value.county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm edit-btn" data-id='${value.id}'>修改</button>
          <button type="button" class="btn btn-danger btn-sm delete-btn" data-id='${value.id}'>删除</button>
        </td>
      </tr>
        `, '')
        let tbody = document.querySelector("tbody")
        tbody.innerHTML = html
      }
    })
    .catch(res => {

    })
}

//为添加学员模态框表单绑定提交事件
let addForm = document.querySelector("#addModal form")
addForm.addEventListener("submit", function (e) {
  e.preventDefault()
  let data = $(this).serialize()
  axios.post('/student/add', data)
    .then(res => {
      let { data: result } = res
      if (result.code === 0) {
        toastr.success(result.message)
        this.reset()
        $('#addModal').modal('hide')
        getStudentList()
      }
    })
    .catch(res => {

    })
})


//为学员列表编辑按钮绑定点击事件
let tbody = document.querySelector("tbody")
tbody.addEventListener("click", async function (e) {
  let target = e.target
  if (target.nodeName === 'BUTTON' && target.classList.contains("edit-btn")) {
    //模态框显示
    $('#updateModal').modal('show');
    //根据学生id查询学生信息
    let res = await axios.get('/student/one', {
      params: {
        id: target.dataset.id
      }
    })
      .catch(res => {

      })

    let { data: studentObj } = res.data
    for (let key in studentObj) {
      // 当遍历属性为sex时,单独处理
      if (key === 'sex') {
        document.querySelector(`#updateModal [name=${key}][value=${studentObj[key]}]`).checked = true
        continue
      }
      //常规表单赋值处理
      let dom = document.querySelector(`#updateModal [name=${key}]`)
      if (dom) {
        dom.value = studentObj[key]
      }
    }


    //渲染学员省份对应下市级

    await renderSelect('/geo/city', document.querySelector(`#updateModal select[name=city]`), '市', {
      pname: studentObj.province
    })

    //设置学员的下拉框市级
    document.querySelector(`#updateModal select[name=city]`).value = studentObj.city



    //渲染学员省份和市级对应下县级
    await renderSelect('/geo/county', document.querySelector(`#updateModal select[name=county]`), '县', {
      pname: studentObj.province,
      cname: studentObj.city
    })

    //设置学员的下拉框县级
    document.querySelector(`#updateModal select[name=county]`).value = studentObj.county

  }
})


//为学员列表删除按钮绑定点击事件
tbody.addEventListener("click", function (e) {

  let target = e.target
  let id = target.dataset.id
  if (target.nodeName === 'BUTTON' && target.classList.contains("delete-btn")) {

    if (confirm('确定删除吗')) {
      axios.delete('/student/delete', {
        params: {
          id
        }
      })
        .then(res => {
          let { data: result } = res
          if (result.code === 0) {
            toastr.success(result.message);
            getStudentList()
          }
        })
        .catch(res => {

        })
    }

  }

})


//为修改学员模态框表单绑定提交事件
let updateForm = document.querySelector("#updateModal form")
updateForm.addEventListener("submit", function (e) {
  e.preventDefault()
  let data = $(this).serialize()
  axios.put('/student/update', data)
    .then(res => {
      let { data: result } = res
      if (result.code === 0) {
        toastr.success(result.message)
        this.reset()
        $('#updateModal').modal('hide')
        getStudentList()
      }
    })
    .catch(res => {

    })
})
